cur_pos = f(1,i);
cur_fsize = 240;
%cur_fsize = f(2,i)-f(1,i)+1;

display(cur_pos);
display(cur_fsize);

% find the best correlation
cscale = sum( data(cur_pos+(1:cur_fsize), 2:end) .* data(cur_pos+(1:cur_fsize), 2:end), 1) ...
     - mean(data(cur_pos+(1:cur_fsize), 2:end), 1) .^ 2 * cur_fsize;
% go left first
cc = zeros(601,1);
cdat = zeros(601, size(data, 2));
for inc = 40:1:640
    %c = zeros(2);
    %for i=2:size(data, 2)
    %    c = corrcoef(data(cur_pos+(1:cur_fsize), i), data(cur_pos+inc+(1:cur_fsize), i));
    %    cdat(inc-40+1, i) = c(1,2);
    %end
    cscale2 = sum( data(cur_pos+inc+(1:cur_fsize), 2:end) .* data(cur_pos+inc+(1:cur_fsize), 2:end), 1) ...
         - mean(data(cur_pos+inc+(1:cur_fsize), 2:end), 1) .^ 2 * cur_fsize;
    c = sum(data(cur_pos+(1:cur_fsize), 2:end) .* data(cur_pos+inc+(1:cur_fsize), 2:end), 1);
    c = c - cur_fsize .* mean(data(cur_pos+inc+(1:cur_fsize), 2:end), 1) .* mean(data(cur_pos+(1:cur_fsize), 2:end), 1);
    c = c ./ sqrt(cscale .* cscale2);
    c(isnan(c))=0;
    c = sum(c);
    cc(inc-40+1) = c;
end
%cc = sum(cdat, 2);

figure;
plot(cc);
%hold;
%plot(cdat);

carray = cc;
cmax = max(carray);
cmin = min(carray);

thres = 0.9 * (cmax - cmin) + cmin;
i = (carray > thres);
i = diff(i);
lb = find(i == 1, 1);
if isempty(lb); lb = 1; end;
rb = find(i(lb:end) == -1, 1) + lb - 1;
if isempty(rb); rb = length(i); end;
[cmax cmax_i] = max(carray(lb:rb));
cmax_i = cmax_i + lb -1;

display(cmax_i);
